"""
Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.
"""

class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def findMin(self, nums):
        if not nums:
            return 0
        ans = nums[0]
        beg = 0
        end = len(nums)-1

        while beg < end:
            mid = (beg+end)/2
            ans = min(ans, nums[beg])
            ans = min(ans, nums[end])
            ans = min(ans, nums[mid])

            if nums[end] >= nums[beg] and nums[mid] >= nums[beg]:
                break

            elif nums[beg] >= nums[end] and nums[mid] >= nums[beg]:
                beg = mid + 1
                end = end - 1
                continue
            
            elif nums[beg] >= nums[end] and nums[mid] <= nums[beg]:
                beg = beg + 1
                end = mid - 1
                continue
        return min(ans, nums[beg])

if __name__ == '__main__':
    print Solution().findMin([4, 5, 6, 7, 0, 1, 2])
    print Solution().findMin([2, 1])
    print Solution().findMin([3, 4, 5, 1, 2])
